import {createRouter, createWebHistory} from 'vue-router'
import UserRoutes from './user'
import AdminRoutes from './admin'
import Login from '../views/common/Login.vue'
import {useUserStore} from '../stores/user/user.js'

const ROLE_USER = 'user';
const ROLE_ADMIN = 'admin';

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/login',
            name: 'login',
            component: Login,
            meta: {requiresAuth: false} // 不需要登录
        },
        {
            path: '/',
            redirect: '/user/home',
        },
        {
            path: '/user',
            component: () => import('../layouts/UserLayout.vue'),
            children: UserRoutes,
            meta: {requiresAuth: true, role: ROLE_USER} // 需要登录，用户角色
        },
        {
            path: '/admin',
            component: () => import('../layouts/AdminLayout.vue'),
            children: AdminRoutes,
            meta: {requiresAuth: true, role: ROLE_ADMIN} // 需要登录，管理员角色
        },
        {
            path: '/:pathMatch(.*)*',
            name: 'NotFound',
            component: () => import('../views/common/NotFound.vue')
        }, {
            path: '/403',
            name: 'Forbidden',
            component: () => import('../views/common/Forbidden.vue')
        }
    ]
})

router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore();
    const isLoggedIn = userStore.isLoggedIn;
    const userRole = userStore.role;
    if (to.meta.requiresAuth) {
        if (!isLoggedIn) {
            next({name: 'login', query: {redirect: to.fullPath}});
        } else {
            if (!userRole) {
                try {
                    await userStore.getInfo();
                    if (to.meta.role && userRole !== to.meta.role) {
                        next({name: 'Forbidden'});
                    } else {
                        next();
                    }
                } catch (error) {
                    await userStore.resetToken();
                    next({name: 'login', query: {redirect: to.fullPath}});
                }
            } else {
                if (to.meta.role && userRole !== to.meta.role) {
                    next({name: 'Forbidden'});
                } else {
                    next();
                }
            }
        }
    } else {
        next();
    }
});

export default router